package com.ifp.opengate.boot.task;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.ifp.opengate.boot.bean.ValidatorForm;
import com.ifp.opengate.boot.utils.RedisUtils;

/**
 * <p>
 * 报文投初始化缓存
 * </P>
 *
 * @author zhuzh@belink.com
 * @version 0.0.1
 * @className HeaderTemplateCacheTask
 * @sine 2020/5/21 15:07
 */
@Component
public class HeaderTemplateCacheTask implements ApplicationRunner {

    @Autowired
    RedisUtils redisUtils;

    @Value("${opengate_header_group_redis_key}")
    String headerGroupRedisKey;

    @Value("${opengate_header_group_redis_paramJson}")
    String headerJson;

    ConcurrentMap<String, List<ValidatorForm>> headerCache = new ConcurrentHashMap<>(216);

    public ConcurrentMap<String, List<ValidatorForm>> getHeaderCache() {
        return headerCache;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.initHeaderTemplates();
    }

    private void initHeaderTemplates() {
        Map<Object, Object> redisKeys = redisUtils.hmget(headerGroupRedisKey);
        redisKeys.keySet().forEach(it -> {
            this.deployHeader((String)it);
        });
    }

    /**
     * 发布报文头
     * 
     * @param headerKey
     */
    private void deployHeader(String headerKey) {
        String headerStr = (String)redisUtils.get(headerKey);
        if (StringUtils.hasText(headerStr)) {
            List<ValidatorForm> validatorForms = JSON.parseArray(headerStr, ValidatorForm.class);
            headerCache.put(headerKey, validatorForms);
        }
    }

    /**
     * 删除报文头
     * 
     * @param headerKey
     */
    public void delHeader(String headerKey) {
        headerCache.remove(headerKey);
    }
}
